%ifndef HEAP_ASM
%define HEAP_ASM

%include "syscalls.asm"

section .bss	align=8
heap1	resq	1024
heap1_end:

heap2	resq	1024
heap2_end:

section	.data
heap_ptr	dq heap1
heap_end	dq heap1_end

err2_1_ty	db	"ERROR 2. HEAP OVERFLOW."
err2_1_len:

section .text

heap_alloc:
	;; INPUT: rax is how much space we want (1 = 1 word = 8 bytes)
	;; OUTPUT: rax points into heap, providing that space

	;; CONDITIONS: bltn_cons depends on this function not trashing
	;; the r9 register
	;; alloc closure depends on it not trashing r8
	
	lea	rcx, [8*rax]
	mov	rax, [heap_ptr]
	add	rcx, [heap_ptr]
	
	cmp	rcx, [heap_end]
	jge	.heap_overflow
	
	;; update the heap_ptr
	mov	[heap_ptr], rcx
	
	ret

.heap_overflow:
	mov	rax, sys_write
	mov	rdi, 0
	mov	rsi, err2_1_ty
	mov	rdx, (err2_1_len - err2_1_ty)
	syscall
	
	mov	rax, sys_exit
	mov	rdi, 1
	syscall

%endif
